use crate::var::dir::ROOT;
use std::fs;

pub trait Bytes {
  fn to_bytes(&self) -> Vec<u8>;
  fn from_bytes(buf: &[u8]) -> Self;
}

impl Bytes for u16 {
  fn to_bytes(&self) -> Vec<u8> {
    self.to_le_bytes().to_vec()
  }

  fn from_bytes(buf: &[u8]) -> Self {
    u16::from_le_bytes(buf[..2].try_into().unwrap())
  }
}

pub fn get<T: Bytes>(file: &str, init: fn() -> T) -> T {
  let path = ROOT.clone().join(file);
  let _init = || {
    let r = init();
    let mut dir = path.clone();
    dir.pop();
    fs::create_dir_all(dir).unwrap();
    fs::write(&path, &r.to_bytes()).unwrap();
    r
  };

  match fs::read(&path) {
    Ok(buf) => T::from_bytes(&buf),
    Err(_) => _init(),
  }
}
